package cluster.old;

import java.util.*;

import cluster.Clusterable;
import cluster.Duster;
public class LookupArray<E extends Clusterable> {
	ArrayList<ArrayList<Link<E>>> list;
	
	public LookupArray(int size){
		list = new ArrayList<ArrayList<Link<E>>>(size);
		ensureCapacity(size-1, list);
	}
	
	public void init(ArrayList<Duster<E>> l){
		Iterator<Duster<E>> i = l.iterator();
		while(i.hasNext()) addDistances(i.next(), l);
	}
	public void addDistance(Duster<E> d1, Duster<E> d2, float distance){
		Duster<E> dMin = d1;
		Duster<E> dMax = d2;
		if(d1.ID > d2.ID){
			dMin = d2;
			dMax = d1;
		}
		ensureCapacity(dMin.ID, dMax.ID);
		list.get(dMin.ID).set(dMax.ID, new Link<E>(dMin, dMax, distance));
	}
	
	public void addDistances(Duster<E> d, ArrayList<Duster<E>> list){
		//if(d.lookup == null) d.lookup = this;
		//d.lookup = this;
		Iterator<Duster<E>> i = list.iterator();
		while(i.hasNext()){
			Duster<E> next = i.next();
			if(d.ID != next.ID)
				addDistance(d, next, d.getDistanceTo(next));
		}
	}
	
	@SuppressWarnings("unchecked")
	private void ensureCapacity(int index, ArrayList list){
		if(list == null) list = new ArrayList();
		int steps = index - (list.size() - 1);
		if(steps < 0) return;
		for(int i = 0; i < steps; i++) list.add(null);
	}
	
	private void ensureCapacity(int id1, int id2){
		ensureCapacity(id1, list);
		ensureCapacity(id2, list.get(id1));
	}
	
	public void sort(){
		
	}
	

	
	public class Link<E extends Clusterable> implements Comparable{
		Duster<E> d1, d2;
		float cost;
		boolean available;
		public Link(Duster<E> d1, Duster<E> d2, float cost) {
			super();
			this.d1 = d1;
			this.d2 = d2;
			this.cost = cost;
			available = true;
		}
		
		
		
		
		
		
		@Override
		public int hashCode() {
			final int PRIME = 31;
			int result = 1;
			result = PRIME * result + ((d1 == null) ? 0 : d1.hashCode());
			result = PRIME * result + ((d2 == null) ? 0 : d2.hashCode());
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			final Link other = (Link) obj;
			if (d1 == null) {
				if (other.d1 != null)
					return false;
			} else if (!d1.equals(other.d1))
				return false;
			if (d2 == null) {
				if (other.d2 != null)
					return false;
			} else if (!d2.equals(other.d2))
				return false;
			return true;
		}

		@SuppressWarnings("unchecked")
		public int compareTo(Object arg0) {
			Link<E> b = (Link<E>)arg0;
			if(b.available != available){
				if(available = false) return -1;
				if(b.available = false) return 1;
			}
			if(cost < b.cost) return -1;
			if(cost > b.cost) return 1;
			return 0;
		}	
	}
}
